package com.yb0os1.handler;

import com.yb0os1.constant.MessageConstant;
import com.yb0os1.exception.BaseException;
import com.yb0os1.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class ExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @org.springframework.web.bind.annotation.ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 重复插入的问题
     */
    @org.springframework.web.bind.annotation.ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        String msg = ex.getMessage();
        if (msg.contains("Duplicate entry")){
            String m = msg.split(" ")[2] + MessageConstant.ALREADY_EXISTS;
            return Result.error(m);
        }else{
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }
}
